package com.seya.calculite.app;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Address;
import android.location.Geocoder;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.List;
import java.util.Locale;


public class LoginActivity extends Activity {

    Button btn_login;
    GPSTracker gps;
    Boolean network_state;
    Boolean location_state = false;
    ProgressDialog pDialog;
    String location;
    double longitude, latitude;
    SharedPreferences prefs;
    Context c;
    EditText userId;
    Boolean isValidId = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        overridePendingTransition(R.anim.activity_open_translate,R.anim.activity_close_scale);
        setContentView(R.layout.activity_login);
        FontHelper.applyFont(this, findViewById(R.id.activity_main_root), "RobotoLight.ttf");
        SplashScreenActivity.loggingOut = false;
        c = getApplicationContext();
        gps = new GPSTracker(LoginActivity.this);
        userId = (EditText) findViewById(R.id.edit_userid);

        btn_login = (Button)findViewById(R.id.btn_login);
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(userId.getText().toString().equals("")){
                    userId.setError("Field cannot be empty");
                }
                else {
                    for (int i = 0; i < SplashScreenActivity.login_ids.length; i++) {
                        if (SplashScreenActivity.login_ids[i].equals(userId.getText().toString())) {
                            isValidId = true;
                            //Toast.makeText(getApplicationContext(), SplashScreenActivity.login_ids[i],Toast.LENGTH_SHORT).show();
                            prefs = c.getSharedPreferences(SplashScreenActivity.SHARED_PREFERENCES_NAME, MODE_PRIVATE);
                            SharedPreferences.Editor editor = prefs.edit();
                            editor.putString(SplashScreenActivity.LOGIN_ID, SplashScreenActivity.login_ids[i]);
                            editor.commit();
                        }
                    }

                    if (isValidId) {
                        if (gps.canGetLocation()) {
                            location_state = true;
                            latitude = gps.getLatitude();
                            longitude = gps.getLongitude();
                        }
                        network_state = isNetworkOnline();
                        if (network_state && location_state) {
                            new GetLocation().execute();
                        } else {
                            Toast.makeText(c, "Turn ON Network and Location to proceed", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        userId.setError("Invalid User ID");
                    }
                }
            }
        });
    }

    private class GetLocation extends AsyncTask<Void, Void, Void>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(LoginActivity.this);
            pDialog.setMessage("Please wait...Getting Location");
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            if(gps.canGetLocation()){
                Log.d("LOC_long",Double.toString(longitude));
                Log.d("LOC_lat",Double.toString(latitude));
                prefs = c.getSharedPreferences(SplashScreenActivity.SHARED_PREFERENCES_NAME, MODE_PRIVATE);
                Editor editor = prefs.edit();
                //Save it as a float since SharedPreferences can't deal with doubles
                editor.putString(SplashScreenActivity.START_LATITUDE, Double.toString(latitude));
                editor.putString(SplashScreenActivity.START_LONGITUDE, Double.toString(longitude));
                editor.commit();
                try {
                    Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
                    List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
                    if (addresses.size() > 0) {
                        location = addresses.get(0).getThoroughfare() + ", "+addresses.get(0).getSubLocality() + ", " +
                                    addresses.get(0).getLocality() + ", "+addresses.get(0).getPostalCode();
                    }
                }
                catch (Exception e) {
                    location_state = false;
                }
            }
            else {
                location_state = false;
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            if (pDialog.isShowing())
                pDialog.dismiss();
            if(network_state && location_state) {

                Intent i = new Intent(getApplicationContext(), InputActivity.class);
                i.putExtra("location", location);
                startActivity(i);
                finish();
            }else {
                Toast.makeText(c,"Network error", Toast.LENGTH_SHORT).show();
            }
        }
    }

    public boolean isNetworkOnline() {
        boolean status=false;
        try{
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getNetworkInfo(0);
            if (netInfo != null && netInfo.getState()==NetworkInfo.State.CONNECTED) {
                status= true;
            }else {
                netInfo = cm.getNetworkInfo(1);
                if(netInfo!=null && netInfo.getState()==NetworkInfo.State.CONNECTED)
                    status= true;
            }
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }
        return status;
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        //closing transition animations
        overridePendingTransition(R.anim.activity_open_scale,R.anim.activity_close_translate);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        SplashScreenActivity.loggingOut = true;
        finish();
    }
}
